import {
  ALL,
  Body,
  Controller,
  Del,
  Get,
  HttpCode,
  Inject,
  Param,
  Post,
  Provide,
  Put,
  Query,
  Validate,
} from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import { DepartmentDto } from '../dto';
import { Department } from '../entity/Department';
import { IBaseQuery } from '../interface';
import * as _ from 'lodash';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/orm';

@Provide()
@Controller('/departments', { tagName: '部门管理' })
export class DepartmentController {
  @Inject()
  ctx: Context;

  @InjectEntityModel(Department)
  departmentModel: Repository<Department>;

  @Get('/', { summary: '获取部门列表' })
  async index(@Query(ALL) query: IBaseQuery) {
    if (query.findAll) {
      return this.departmentModel.find({
        where: _.pick(query, ['name']),
      });
    }
    const [rows, count] = await this.departmentModel.findAndCount({
      where: _.pick(query, ['name']),
      skip: query.offset || 0,
      take: query.limit || 10,
    });
    return { rows, count };
  }

  @Get('/:id', { summary: '获取部门详情' })
  async show(@Param() id: number) {
    const result = await this.departmentModel.findOne(id);
    return result;
  }

  @Post('/', { summary: '创建部门' })
  @Validate()
  async create(@Body(ALL) body: DepartmentDto) {
    // 检查名称是否重复
    const isExist = await this.departmentModel.findOne({
      name: body.name,
    });
    if (isExist) {
      this.ctx.throw(400, '部门名称已存在');
    }
    const instance = await this.departmentModel.create(body);
    await this.departmentModel.save(instance);
    return instance;
  }

  @Put('/:id', { summary: '更新部门' })
  async update(@Param() id: number, @Body(ALL) body: DepartmentDto) {
    const instance = await this.departmentModel.findOne(id);
    if (!instance) {
      this.ctx.throw(404, '对象不存在');
    }
    this.departmentModel.merge(instance, body);
    await this.departmentModel.save(instance);
    return instance;
  }

  @Del('/:id', { summary: '删除部门' })
  @HttpCode(204)
  async delete(@Param() id: number) {
    const instance = await this.departmentModel.findOne(id);
    if (instance) {
      await this.departmentModel.softRemove(instance);
    }
  }
}
